<?php
class Qa_BrandruleController extends Baogg_Controller_Action {
	
	function init() {
	}
	function listAction() {
		
		global $LANG;
		$params = $this->getRequest ()->getParams ();
		$form_url = $params;
		Zend_Loader::loadClass ( "Baogg_View_Extgrid" );
		$Dict = new Dict ();
		//echo __FILE__.__LINE__."<pre>";print_r($rs_model_field);exit;
		$form_url ["action"] = "combo";
		$str_combo_url = Baogg_Controller_Url::generate ( $form_url );
		$cm ["rule_id"] = array ("sortable" => true );
		$cm ['rule_id']["cmType"]=Baogg_View_Extgrid::CMTYPE_PK;
		$cm ["rule_name"] = array ("sortable" => true );
		$cm ["description"] = array ("sortable" => true );
		$cm ["original"] = array ("sortable" => true );
		$cm ["compile"] = array ("sortable" => true );
		$cm ["sql_fn"] = array ("sortable" => true );
		$cm ["is_group_by_fn"] = array ("sortable" => true );
		$cm ["is_group_by_fn"] ["xtype"] = "templatecolumn";
		$cm ["is_group_by_fn"] ["tpl"] = "{is_group_by_fn2}";
		$cm ["is_group_by_fn2"] = array ("hidden" => true );
		$cm ["rule_type_id"] = array ("sortable" => true );
		$cm ["state"] = array ("sortable" => true );
		$cm ["state"] ["xtype"] = "templatecolumn";
		$cm ["state"] ["tpl"] = "{state2}";
		$cm ["state2"] = array ("hidden" => true );
		$cm ["ordering"] = array ("sortable" => true );
		$cm ["qa_brand_id"] = array ("sortable" => true );
		$cm ["qa_brand_id"] ["xtype"] = "templatecolumn";
		$cm ["qa_brand_id"] ["tpl"] = "{qa_brand_id2}";
		$cm ["qa_brand_id2"] = array ("hidden" => true );
		$cm ["qa_rule_id"] = array ("sortable" => true );
		$cm ["qa_rule_id"] ["xtype"] = "templatecolumn";
		$cm ["qa_rule_id"] ["tpl"] = "{qa_rule_id2}";
		$cm ["qa_rule_id2"] = array ("hidden" => true );
		$cm ["qa_field_ids"] = array ("sortable" => true );
		$cm ["qa_surveys_id"] = array ("sortable" => true );
		$cm ["qa_surveys_id"] ["xtype"] = "templatecolumn";
		$cm ["qa_surveys_id"] ["tpl"] = "{qa_surveys_id2}";
		$cm ["qa_surveys_id2"] = array ("hidden" => true );
		$cm ["compile_sql"] = array ("sortable" => true );
		$form_url ["action"] = "data";
		$grid = new Baogg_View_Extgrid ( $form_url, $cm );
		$grid->setSelectionModel ( false );
		$grid->setRowNumberer ( true );
		$grid->addExistButtons ( array ("add", "remove", "query" ), array ("edit", "delete" ) );
		$form_url ["action"] = "add";
		$form = new Baogg_View_Extform ( array ("url" => $form_url, "height" => 600, "width" => 600 ) );
		
		$form_items ["rule_id"] = array ("xtype" => "hidden" );
		$form_items ["rule_name"] = array ("xtype" => "textfield" );
		$form_items ["rule_name"] = array ("xtype" => "combo", "hideTrigger" => true, "mode" => "remote", "queryMode" => "remote", "minChars" => 1, "valueField" => "rule_name", "displayField" => "rule_name", "forceSelection" => false, "allowBlank" => true, "store" => new Zend_Json_Expr ( 'new Ext.data.JsonStore({root: "data",totalProperty: "count",idProperty: "rule_name",remoteSort: true,fields: ["rule_name"],autoLoad:true,proxy: new Ext.data.HttpProxy({type:"ajax",actionMethods: { create : "POST", read : "POST", update : "POST", destroy: "POST" }, reader: {	 type: "json", 	 totalProperty: "count", root: "data"},url: "' . $str_combo_url . 'model_field_id/410/"})})' ), "pageSize" => Baogg_View_Extgrid::$PAGE_SIZE );
		$form_items ["description"] = array ("xtype" => "textarea" );
		$form_items ["original"] = array ("xtype" => "textarea" );
		$form_items ["compile"] = array ("xtype" => "textarea" );
		$form_items ["sql_fn"] = array ("xtype" => "textarea" );
		$form_items ["compile_sql"] = array ("xtype" => "textarea" );
		$form_items ["is_group_by_fn"] = array ("xtype" => "radiogroup" );
		$form_items ["is_group_by_fn"] ["source"] = $Dict->getDictCombo ( "1" );
		$form_items ["state"] = array ("xtype" => "radiogroup" );
		$form_items ["state"] ["source"] = $Dict->getDictCombo ( "1" );
		$form_items ["ordering"] = array ("xtype" => "textfield" );
		$form_items ["ordering"] = array ("xtype" => "combo", "hideTrigger" => true, "mode" => "remote", "queryMode" => "remote", "minChars" => 1, "valueField" => "ordering", "displayField" => "ordering", "forceSelection" => false, "allowBlank" => true, "store" => new Zend_Json_Expr ( 'new Ext.data.JsonStore({root: "data",totalProperty: "count",idProperty: "ordering",remoteSort: true,fields: ["ordering"],autoLoad:true,proxy: new Ext.data.HttpProxy({type:"ajax",actionMethods: { create : "POST", read : "POST", update : "POST", destroy: "POST" }, reader: {	 type: "json", 	 totalProperty: "count", root: "data"},url: "' . $str_combo_url . 'model_field_id/418/"})})' ), "pageSize" => Baogg_View_Extgrid::$PAGE_SIZE );
		$form_items ["qa_brand_id"] = array ("xtype" => "combo" );
		$form_items ["qa_brand_id"] ["store"] = $Dict->getDictCombo ( "5" );
		$form_items ["qa_rule_id"] = array ("xtype" => "combo" );
		$form_items ["qa_rule_id"] ["store"] = $Dict->getDictCombo ( "6" );
		$form_items ["qa_field_ids"] = array ("xtype" => "itemselector" );
		$form_items ["qa_field_ids"] ["store"] = $Dict->getDictCombo ( "8" );
		$form_items ["qa_surveys_id"] = array ("xtype" => "combo" );
		$form_items ["qa_surveys_id"] ["store"] = $Dict->getDictCombo ( "4" );
		
		$form->addItems ( $form_items );
		$form->addExistButtons ( array ("-", "save_grid", "save_new", "save", "-", "search", "-", "cancel" ) );
		
		$this->view->form = $form;
		
		$this->view->LANG = Zend_Json::encode ( $LANG );
		$this->view->grid = $grid->render ();
	}
	function dataAction() {
		$params = $this->getRequest ()->getParams ();
		
		$instance = new Rule ();
		$where = array ();
		$order = array ();
		$limit = array ();
		foreach ( ( array ) $params as $k => $v ) {
			if ($k == "start" || $k == "limit") {
				$limit [$k] = $v;
			} else if ($k == "sort" || $k == "dir") {
				$order [$k] = $v;
			} else {
				if ($k == $instance->myPrimary) {
					if ($v && is_numeric ( $v )) {
						$v = ( int ) $v;
						$where [$k] = $v;
					}
				} else {
					$v = "%" . $v . "%";
					$where [$k] = $v;
				}
			
			}
		}
		
		$rs = $instance->getList ( $where, $order, $limit );
		$Dict = new Dict ();
		$arr_dict = array ();
		foreach ( ( array ) $rs as $k => $v ) {
			if (isset ( $v ["is_group_by_fn"] )) {
				if (! isset ( $arr_dict ["1"] )) {
					$rs_dict = $Dict->getDictCombo ( "1" );
					$arr_dict ["1"] = array ();
					foreach ( $rs_dict as $v_dict ) {
						$arr_dict ["1"] [$v_dict [0]] = $v_dict [1];
					}
				}
				if (isset ( $arr_dict ["1"] [$v ["is_group_by_fn"]] )) {
					$rs [$k] ["is_group_by_fn2"] = $arr_dict ["1"] [$v ["is_group_by_fn"]];
				}
			}
			if (isset ( $v ["state"] )) {
				if (! isset ( $arr_dict ["1"] )) {
					$rs_dict = $Dict->getDictCombo ( "1" );
					$arr_dict ["1"] = array ();
					foreach ( $rs_dict as $v_dict ) {
						$arr_dict ["1"] [$v_dict [0]] = $v_dict [1];
					}
				}
				if (isset ( $arr_dict ["1"] [$v ["state"]] )) {
					$rs [$k] ["state2"] = $arr_dict ["1"] [$v ["state"]];
				}
			}
			if (isset ( $v ["qa_brand_id"] )) {
				if (! isset ( $arr_dict ["5"] )) {
					$rs_dict = $Dict->getDictCombo ( "5" );
					$arr_dict ["5"] = array ();
					foreach ( $rs_dict as $v_dict ) {
						$arr_dict ["5"] [$v_dict [0]] = $v_dict [1];
					}
				}
				if (isset ( $arr_dict ["5"] [$v ["qa_brand_id"]] )) {
					$rs [$k] ["qa_brand_id2"] = $arr_dict ["5"] [$v ["qa_brand_id"]];
				}
			}
			if (isset ( $v ["qa_rule_id"] )) {
				if (! isset ( $arr_dict ["6"] )) {
					$rs_dict = $Dict->getDictCombo ( "6" );
					$arr_dict ["6"] = array ();
					foreach ( $rs_dict as $v_dict ) {
						$arr_dict ["6"] [$v_dict [0]] = $v_dict [1];
					}
				}
				if (isset ( $arr_dict ["6"] [$v ["qa_rule_id"]] )) {
					$rs [$k] ["qa_rule_id2"] = $arr_dict ["6"] [$v ["qa_rule_id"]];
				}
			}
			if (isset ( $v ["qa_field_ids"] )) {
				if (! isset ( $arr_dict ["8"] )) {
					$rs_dict = $Dict->getDictCombo ( "8" );
					$arr_dict ["8"] = array ();
					foreach ( $rs_dict as $v_dict ) {
						$arr_dict ["8"] [$v_dict [0]] = $v_dict [1];
					}
				}
				if (isset ( $arr_dict ["8"] [$v ["qa_field_ids"]] )) {
					$rs [$k] ["qa_field_ids2"] = $arr_dict ["8"] [$v ["qa_field_ids"]];
				}
			}
			if (isset ( $v ["qa_surveys_id"] )) {
				if (! isset ( $arr_dict ["4"] )) {
					$rs_dict = $Dict->getDictCombo ( "4" );
					$arr_dict ["4"] = array ();
					foreach ( $rs_dict as $v_dict ) {
						$arr_dict ["4"] [$v_dict [0]] = $v_dict [1];
					}
				}
				if (isset ( $arr_dict ["4"] [$v ["qa_surveys_id"]] )) {
					$rs [$k] ["qa_surveys_id2"] = $arr_dict ["4"] [$v ["qa_surveys_id"]];
				}
			}
		}
		
		$rs_cnt = $instance->getList ( $where, null, NULL, "count(*) as cnt" );
		
		echo Zend_Json::encode ( array ("count" => $rs_cnt [0] ["cnt"], "data" => $rs ) );
		$this->_helper->viewRenderer->setNoRender ();
	
	}
	function addAction() {
		$this->saveAction ();
	}
	
	function editAction() {
		$this->saveAction ();
	}
	
	function deleteAction() {
		
		$ret = array ("success" => false, "msg" => "delete_fail" );
		$id = Baogg_Controller_Action::_getParam ( "ids" );
		
		$instance = new Rule ();
		
		if ($instance->_delete ( $id )) {
			$ret ["success"] = true;
			$ret ["msg"] = "delete_ok";
		}
		
		echo Baogg_Language::outputResult ( $ret );
		$this->_helper->viewRenderer->setNoRender ();
	}
	
	function removeAction() {
		$this->deleteAction ();
	}
	
	/**
	 * The save action
	 */
	function saveAction() {
		//global $LANG;
		

		$ret = array ("success" => false, "msg" => "save_fail" );
		
		//check form
		if (! $this->_request->isPost ()) {
			echo Baogg_Language::outputResult ( $ret );
			exit ();
		}
		
		$formData = $this->_request->getPost ();
		
		if (! $formData) {
			echo Baogg_Language::outputResult ( $ret );
			exit ();
		}
		
		$instance = new Rule ();
		
		$arr = $instance->filterForm ( $formData );
		
		$arr_col_id=array();
		


		$arr_orig=$instance->qaCompile($arr['original'],array('qa_surveys_id'=>(int)$formData['qa_surveys_id']));


		$arr['compile']=$arr_orig['compile'];
		
		$arr_col_id=array_merge($arr_col_id,$arr_orig['cols']);
		
		
		


		$arr_orig=$instance->qaCompile($arr['sql_fn'],array('qa_surveys_id'=>(int)$formData['qa_surveys_id']));


		$arr['compile_sql']=$arr_orig['compile'];
		$arr_col_id=array_merge($arr_col_id,$arr_orig['cols']);
		
		$arr['qa_field_ids']=implode(',',$arr_col_id);
		
		$action = $this->getRequest ()->getParam ( "action" );
		//echo __FILE__.__LINE__.'<pre>';print_r($arr);var_dump($arr [$instance->myPrimary]);
		$rs = array();//$instance->getSame2 ( $arr, " and " );
		if ($action == "edit") {
			if (count ( $rs ) == 0 || count ( $rs ) == 1 && $rs [0] == $arr [$instance->myPrimary]) {
				$rule_id=$arr [$instance->myPrimary];
				$instance->_update ( $arr, $arr [$instance->myPrimary] );
				
				$ret ["success"] = true;
				$ret ["msg"] = "save_ok";
			} else {
				$ret ["msg"] = "exist_same_record";
			}
		
		} else {
			//insert record
			//$permission_type = 1;
			if ($rs) {
				$ret ["msg"] = "exist_same_record";
			} else {
				unset ( $arr [$instance->myPrimary] );
				
						
			
				


				$ret ["success"] =($rule_id=$instance->_insert ( $arr )) > 0 ? true : false;

				$ret ["msg"] = "add_ok";
			}
		}
		$rule_file=BAOGG_UPLOAD_DIR . 'rule/'. $rule_id . '.php';
		Baogg_File::mkdir(dirname($rule_file));
		@file_put_contents($rule_file, "<?php \n{$arr['compile']}\n ?>");
		
		echo Baogg_Language::outputResult ( $ret );
		
		$this->_helper->viewRenderer->setNoRender ();
	
	}
}